﻿using System;
using System.Runtime.Serialization;
using System.Linq.Expressions;

namespace ExpressionSerialization
{
  [DataContract]
  public class XNewExpression : XExpression
  {

    [DataMember]
    public object Value { get; set; }


    public override void FromExpression(Expression source_)
    {
      base.FromExpression(source_);
      NewExpression exp = source_ as NewExpression;
      // převedu na Constantu 
      // -- argumenty

      //exp.Arguments
      object[] par = new object[exp.Arguments.Count];
      for(int i=0; i < exp.Arguments.Count; i++) {
        ConstantExpression ce = exp.Arguments[i] as ConstantExpression;
        if(ce == null) throw new Exception("Chyba NewExpression - Parametr není konstanta");
        par[i] = ce.Value;
      }
      object res = exp.Constructor.Invoke(par);

      Value = res;
      //exp.Members
      //Operand = XExpression.CreateFromExpression(unexp.Operand);
    }

    public override Expression ToExpression(Type dataContract_, System.Collections.Generic.List<ParameterExpression> parameters_)
    {
      ConstantExpression res = Expression.Constant(Value);
      //if(Constructor != null)
      //  return Expression.New(Constructor, Arguments.GetExpressions());
      //else
      //  return Expression.New(Type);
      return res;
    }
  }
}
